<!DOCTYPE html>
<html>
    <head>
        <!-- Update title -->
        <title>Flocking: Part 5</title>

        <!-- keywords used for searching -->
        <meta name="keywords" content="guide, flocking, particles">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!-- reference to Cinder classes -->
        <!-- <ci seealso dox="[CLASS NAME GOES HERE]" label="[NAME OF LINK]"></ci> -->

        <!-- master stylesheet - these links will be replaced when compiled -->
        <link rel="stylesheet" href="../../_assets/css/foundation.css">
        <link rel="stylesheet" href="../../_assets/css/prism.css">
        <link rel="stylesheet" href="../../_assets/css/style.css">
        <link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css'>

        <!-- Place additional stylsheet links here, which will be copied over when compiled (optional) -->
        
    </head>

    <body id="guide-contents" class="language-c++">
    
		<h1><a class="anchor" id="evasion"></a>
		RULE 4: EVASION</h1>
		<p><br />
		No longer is our virtual world a peaceful place where objects can flock freely and travel in a blissful nirvana of vortices and happy neighbors wanting for nothing. Now we show them life can be cruel. <br />
		<br />
		</p><div class="image">
		<img src="images/4527424956_9962a3d979_o.jpg" alt="4527424956_9962a3d979_o.jpg"/>
		</div>
		<p> <em>Photo Credit: Bo Pardau (Flickr:bodiver)</em> <br />
		<br />
		Rule 4 is simple enough. If you see a predator coming, run away and fast. We have created a <em>Predator</em> class that is nearly a duplicate of our <em>Particle</em> class (which is the prey in our simulation). In fact, these two classes are so similar many of you more experienced coders will probably be thinking &ldquo;Why not make a flocking class and subclass the Predators and Prey&amp;rdquo? We definitely should consider this option but for the sake of readability, we are going to leave this as an exercise for the reader. <br />
		 <br />
		</p><div class="image">
		<img src="images/chapter5b.jpg" alt="chapter5b.jpg"/>
		</div>
		<p> <br />
		 <br />
		The <em>Predator</em>s will behave like the other objects in our virtual world. They avoid collisions and loneliness and also try to travel in packs. However, they are also drawn towards the largest clump of prey within their zone radius (which we have defined to be three times the size of the prey's zones). Our <em>Particle</em> prey continue to abide by their three rules but whenever they sense a nearby <em>Predator</em>, they move away from the <em>Predator</em>'s location. <br />
		 <br />
		</p><div class="fragment"><div class="line"><span class="keywordtype">float</span> eatDistSqrd = 10.0f;</div>
		<div class="line"><span class="keywordtype">float</span> predatorZoneRadiusSqrd = zoneRadiusSqrd * 3.0f;</div>
		<div class="line"><span class="keywordflow">for</span>( list::iterator predator = mPredators.begin(); predator != mPredators.end(); ++predator ) {</div>
		<div class="line">  Vec3f dir = p1-&gt;mPos[0] - predator-&gt;mPos[0];</div>
		<div class="line">  <span class="keywordtype">float</span> distSqrd = dir.lengthSquared();</div>
		<div class="line"></div>
		<div class="line">  <span class="keywordflow">if</span>( distSqrd &lt; predatorZoneRadiusSqrd ){</div>
		<div class="line">    <span class="keywordflow">if</span>( distSqrd &gt; eatDistSqrd ){</div>
		<div class="line">        <span class="keywordtype">float</span> F = ( predatorZoneRadiusSqrd/distSqrd - 1.0f ) * 0.1f;</div>
		<div class="line">        p1-&gt;mFear += F * 0.1f;</div>
		<div class="line">        dir = dir.normalized() * F;</div>
		<div class="line">        p1-&gt;mAcc += dir;</div>
		<div class="line">      predator-&gt;mAcc += dir;</div>
		<div class="line">    } <span class="keywordflow">else</span> {</div>
		<div class="line">      p1-&gt;mIsDead = <span class="keyword">true</span>;</div>
		<div class="line">      predator-&gt;mIsHungry = <span class="keyword">false</span>;</div>
		<div class="line">      <span class="comment">// predator-&gt;mHunger -= p1-&gt;mMass;</span></div>
		<div class="line">    }</div>
		<div class="line">  }</div>
		<div class="line"> }</div>
		</div><!-- fragment --><p><br />
		To apply the <em>Predator</em> response, we add another list iterator into the outer nested list of our <em>applyForce()</em> method (which is officially a poorly named method so it is now called <em>applyForceToParticles()</em> and the version for <em>Predator</em>s is called <em>applyForceToPredators()</em> ). For every <em>Particle</em>, check its distance to every <em>Predator</em>. If that distance is small enough, the<em> Particle</em> is eaten (<em>mIsDead = true</em>) and it is removed from the <em>mParticles</em> list in the <em>ParticleController::update()</em> method. Additionally, set the <em>Predator</em>'s hunger boolean to false. Or if we are dealing with a much larger <em>Predator</em>, you could create an <em>mHunger</em> float which increases with each passing frame. Every time the predator is successful at feeding, the <em>mHunger</em> amount decreases by an amount proportional to the size of the eaten prey. <br />
		 <br />
		</p><div class="image">
		<img src="images/chapter5a.jpg" alt="chapter5a.jpg"/>
		</div>
		<p> <br />
		 <br />
		If the distance to the <em>Predator</em> is greater than the eating distance but smaller than the 3x zone radius, this means flee. The <em>Particle</em>'s acceleration vector is greatly influenced by the vector between <em>Particle</em> and <em>Predator</em>. Additionally, the <em>Predator</em>'s acceleration vector is also affected similarly in order to give chase. <br />
		 <br />
		Since our <em>Predator</em>s generally move faster than our <em>Particle</em>s, we have added a fear variable. As the <em>Predator</em> nears, the <em>Particle</em>'s <em>mFear </em>variable increases. This variable is then used to influence the <em>Particle</em>'s maximum speed. <br />
		 <br />
		</p><div class="fragment"><div class="line"><span class="keywordtype">float</span> maxSpeed = <a class="code" href="_cinder_msw_gdi_plus_8h.html#ac6afabdc09a49a433ee19d8a9486056d">math&lt;float&gt;::min</a>( mMaxSpeed + mFear, 5.0f );</div>
		<div class="line"><span class="keywordtype">float</span> maxSpeedSqrd = maxSpeed * maxSpeed;</div>
		</div><!-- fragment --><p><br />
		This doesn't mean the <em>Particle</em> will always outrun the Predator. There is still a cap to the maximum speed burst allowed, but the extra little bit should help prolong the <em>Particle</em>'s life. <br />
		 <br />
		However, the <em>Predator</em> has a corresponding hunger variable. The more time that passes since the <em>Predator</em> last fed, the greater the<em> Predator</em>'s max speed. To summarize: <em>Predator</em>s normally outswim <em>Particle</em>s. When a <em>Particle</em> is scared, it can outswim the <em>Predator</em>. However, if the <em>Predator</em> is hungry enough, it can outswim a frightened <em>Particle</em>. <br />
		 </p>
		<h1><a class="anchor" id="crowding"></a>
		CROWDING</h1>
		<p><br />
		In our flocking simulation, each <em>Particle </em>pays attention to all the neighbor <em>Particle</em>s within a set distance. However, it is theorized that each bird in a flock would pay attention to a limited number of close neighbors. Estimates put this number between 5 and 10. We can fairly quickly simulate this limited neighbor influence theory by allowing each <em>Particle</em> to adjust its zone radius based on how crowded it feels. <br />
		 <br />
		</p><div class="fragment"><div class="line"><span class="keywordtype">float</span> zoneRadiusSqrd = zoneRadius * p1-&gt;mCrowdFactor * zoneRadius * p2-&gt;mCrowdFactor;</div>
		</div><!-- fragment --><p><br />
		Each <em>Particle</em> has its own crowd factor variable which is inversely related to how many neighbors it has. When iterating through the nested lists in <em>applyForceToParticles()</em>, we count the number of close neighbors for each <em>Particle</em>. We can then use that number to adjust the radius of influence for each <em>Particle</em>. We can easily show the how crowded each Particle is by adjusting the color we use to draw the Particle. If the <em>Particle</em> is very crowded, <em>mCrowdFactor</em> decreases and the color shifts to saturated red. If the <em>Particle</em> is very isolated, the <em>mCrowdFactor</em> increases and its color shifts to desaturated purple. This is a fairly straightforward way of giving each <em>Particle</em> its own personality. Though the rules governing the behavior of these<em> Particle</em>s are global, the parameters can easily be individualized. <br />
		 </p>
		<h1><a class="anchor" id="current"></a>
		CURRENT</h1>
		<p><br />
		We are going to add one final element to our flocking code. It is time to reintroduce Perlin noise (which we discussed in Section 1: Chapter 4). If we are simulating birds, the Perlin noise can be tweaked to create a strong breeze. If we are simulating fish, the Perlin dfBm() method can help to facilitate the formation of vortices in our flocking agents. <br />
		 <br />
		</p><div class="fragment"><div class="line"><span class="keywordtype">float</span> <a class="code" href="namespacecinder_1_1dx.html#a2efdb9cb695ff519cf33f82b01fedca8">scale</a> = 0.005f;</div>
		<div class="line"><span class="keywordtype">float</span> multi = 0.1f;</div>
		<div class="line">p1-&gt;mAcc += mPerlin.dfBm( p1-&gt;mPos * scale ) * multi;</div>
		</div><!-- fragment --><p><br />
		All we do is add in a Perlin influence based on the position of each Particle. After we create our Perlin instance and set our controlling variables, all we need is one line of code. Try commenting this line out and seeing if you can notice the difference. Also play around with the scale and multi variables to control the extent to which the Perlin can influence the Particles. <br />
		 </p>
		<h1><a class="anchor" id="conclusion"></a>
		CONCLUSION</h1>
		<p><br />
		Flocking simulations are especially powerful because they allow even beginner programmers to appreciate the complex beauty that arises as a result of emergent behaviors. When you consider the controlled chaos of a flock of tens of thousands of starlings flying in near perfect synchrony, or a tightly packed bait ball of shoaling fish, it confuses the mind. How are they able to avoid collisions? How do they all seem to know when and where to turn? Viewed from a distance, it seems like it would be a near impossible task for a computer to simulate. <br />
		<br />
		 
		<iframe src="https://player.vimeo.com/video/16189742" width="800" height="450" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
		<p><a href="https://vimeo.com/16189742">Starling Flock at the Vatican</a> from <a href="https://vimeo.com/timstutts">Tim Stutts</a> on <a href="https://vimeo.com">Vimeo</a>.</p>
		 <br />
		<br />
		However, when you analyze the problem from inside the group and consider what any one individual is thinking, the problem becomes quite simple. I should avoid crashing into the others around me. I should move in the general direction of my neighbors. If I wander too far from the group, I could die. If I see a predator, I should flee. These are the four basic rules of flock/swarm/shoaling behavior. <br />
		 <br />
		The following video was made with the source code for this chapter. <br />
		<br />
		 
		<iframe src="https://player.vimeo.com/video/16290788" width="800" height="450" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
		<p><a href="https://vimeo.com/16290788">1 vs. 35,000</a> from <a href="https://vimeo.com/flight404">flight404</a> on <a href="https://vimeo.com">Vimeo</a>.</p>
		 <br />
		Further reading: <br />
		</p>
		<p>1.) <a href="http://www.red3d.com/cwr/papers/1987/boids.html">Flocks, Herds, and Schools: A Distributed Behavioral Model</a> by <a href="http://www.red3d.com/cwr/">Craig Reynolds</a><br />
		2.) <a href="http://www.red3d.com/cwr/steer/gdc99/">Steering Behaviors for Autonomous Characters</a> by <a href="http://www.red3d.com/cwr/">Craig Reynolds</a><br />
		3.) Wikipedia entry on <a href="http://en.wikipedia.org/wiki/Shoaling_and_schooling">Shoaling and Schooling</a><br />
		4.) <a href="http://scitation.aip.org/journals/doc/PHTOAD-ft/vol_60/iss_10/28_1.shtml?bypassSSO=1">Statistical Physics is for the Birds</a> by Toni Feder<br />
		<br />
		</p>
		<p>Back to index: <a class="el" href="hello_cinder.html">Tutorial Index</a>.<br />
		<br />
		</p>
		<!-- END CONTENT -->

		<!-- Scripts -->
		<script src="../../_assets/js/prism.js" type="text/javascript"></script>
		<!-- Place additional scripts here (optional) -->
		<!-- <script type="text/javascript"></script> -->

	</body>
</html> 